package com.yzs.exam.config.spring.security;

import com.yzs.exam.entity.User;
import com.yzs.exam.entity.enums.RoleEnum;
import com.yzs.exam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * 记住我功能需要的UserDetailsService实现类
 * 当用户发起认证请求，会通过UsernamePasswordAuthenticationFilter，
 * 在认证成功之后，可以调用SpringSecurity提供的RememberMeService，
 * 它会生成一个Token并将它写入浏览器的Cookie中，
 * 同时这个它里面有一个TokenRepositoryTokenRepository会将Token放入数据库中。
 * 当下次浏览器再请求的时候，会经过RememberMeAuthenticationFiler，
 * 在这个filter里面会读取Cookie中的Token，然后去数据库中查找是否有相应的Token，
 * 然后再通过UserDetailsService获取用户的信息。
 * @author yzs
 * @create 2021-03-21 3:14
 */
@Component
public class RestDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public RestDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUserName(username);
        if (user == null){
            throw new UsernameNotFoundException("Username  not found.");
        }

        //获取用户的权限
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));

        //封装成securtiyUser返回
        return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
    }
}
